package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.exception.UploadException;
import cn.ztydata.teachingsystem.heaven.cons.FileNameCode;
import cn.ztydata.teachingsystem.heaven.service.CourseOverviewService;
import cn.ztydata.teachingsystem.heaven.util.FileConverter;
import cn.ztydata.teachingsystem.heaven.util.UploadUtil;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 上传word
 *
 * @author fanruiping
 * @since 2015-02-05
 */
@RequestMapping("/uploadWord")
@Controller
public class UploadWordController extends BaseController {
    @Autowired
    private CourseOverviewService courseOverviewService;
    @Autowired
    private FileConverter fileConverter;
    @Value("${file.dir}")
    private String uploadDir;
    /**
     * 上传课程概况word
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-02-05
     */
    @RequestMapping(value = "/lessonWord/{id}/{type}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult lessonWord(@PathVariable int id, @PathVariable int type,@RequestParam("wordFile") MultipartFile coverFile){
        //定义允许上传的图片类型
        List fileTypes = Lists.newArrayList("doc","docx");
        String url = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(coverFile, fileTypes);

            //保存上传的图片
            String fileExt = UploadUtil.getFileExt(coverFile.getOriginalFilename());

            //生成文件上传地址
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            url = "/"+sdf.format(new Date())+"/"+ UploadUtil.generateFileName(fileExt);

            File file = new File(uploadDir, url);
            FileUtils.writeByteArrayToFile(file, coverFile.getBytes());

            courseOverviewService.updateFile(id,type,url);

            fileConverter.newTask("course:" + FileNameCode.courseMap.get(type) + ":" + id);

            log.debug("word文件上传成功");

            return new JsonResult(true,"word文件上传成功");
        } catch (IOException ex) {
            log.debug("word文件上传异常:IOException");

            log.warn("word文件上传失败:url->" + url, ex);

            return new JsonResult(false, "文件转换失败");
        } catch (UploadException | ServiceException ex) {
            log.debug("word文件上传异常:UploadException|ServiceException");

            return new JsonResult(false, ex.getMessage().isEmpty() ? "上传失败" : ex.getMessage());
        }
    }

    /**
     * 删除课程概况word
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-02-05
     */
    @RequestMapping(value = "/deleteLesson/{id}/{type}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult deleteLesson(@PathVariable int id, @PathVariable int type){
        try {
            courseOverviewService.deleteFile(id,type);
        } catch (ServiceException ex) {
            log.debug("word文件删除异常:ServiceException");

            return new JsonResult(false, ex.getMessage().isEmpty() ? "删除失败" : ex.getMessage());
        }

        log.debug("word文件删除成功");

        return new JsonResult(true,"word文件删除成功");
    }

    /**
     * 转换课程概况word
     * @param id 课程编号
     * @param type 概况类型
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-02-06
     */
    @RequestMapping(value = "/transformLesson/{id}/{type}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult transformLesson(@PathVariable int id, @PathVariable int type){
        try {
            fileConverter.newTask("course:" + FileNameCode.courseMap.get(type) + ":" + id);

            log.debug("word文件转换成功");

            return new JsonResult(true, "文件正在转换，请刷新查看");
        }catch (IOException ex){
            log.debug("word文件IO异常");

            return new JsonResult(false, "转换失败");
        }
    }
}
